const mysql = require('mysql2/promise');
const config = require('./database-config.js');

/**
 * 补充乾坤珠属性数据脚本
 */

async function addQiankunGemAttributes() {
    let connection;

    try {
        console.log('🔮 开始补充乾坤珠属性数据...');

        // 连接数据库
        connection = await mysql.createConnection(config.source);
        console.log('✅ 数据库连接成功');

        // 乾坤珠属性数据
        const qiankunAttributes = [
            { gemId: 15, attributeName: '连击率', equipmentSlots: '2,5', maxValue: 12 },
            { gemId: 15, attributeName: '连击数', equipmentSlots: '2,5', maxValue: 3 },
            { gemId: 15, attributeName: '暴击率', equipmentSlots: '2,5,6', maxValue: 15 }
        ];

        // 插入乾坤珠属性数据
        console.log('\n1️⃣ 插入乾坤珠属性数据...');
        const insertSQL = `
      INSERT INTO \`gem_attributes\` (\`gem_id\`, \`attribute_name\`, \`equipment_slots\`, \`max_value\`, \`created_at\`) 
      VALUES (?, ?, ?, ?, NOW())
    `;

        for (const attr of qiankunAttributes) {
            await connection.execute(insertSQL, [attr.gemId, attr.attributeName, attr.equipmentSlots, attr.maxValue]);
            console.log(`  ✅ 插入: ${attr.attributeName} (最大${attr.maxValue}, 槽位${attr.equipmentSlots})`);
        }

        // 验证插入结果
        console.log('\n2️⃣ 验证插入结果...');
        const [qiankunData] = await connection.execute(`
      SELECT ga.*, gb.name as gem_name 
      FROM \`gem_attributes\` ga 
      JOIN \`gem_base\` gb ON ga.gem_id = gb.id 
      WHERE gb.name = '乾坤珠'
      ORDER BY ga.attribute_name
    `);

        console.log('\n📋 乾坤珠属性数据:');
        qiankunData.forEach(attr => {
            console.log(`  - ${attr.attribute_name}: 最大${attr.max_value}, 槽位${attr.equipment_slots}`);
        });

        // 统计更新
        const [totalCount] = await connection.execute('SELECT COUNT(*) as count FROM `gem_attributes`');
        console.log(`\n📊 宝石属性表总记录数: ${totalCount[0].count}`);

        console.log('\n🎉 乾坤珠属性数据补充完成！');

    } catch (error) {
        console.error('❌ 补充失败:', error.message);
        if (error.code) {
            console.error('错误代码:', error.code);
        }
        throw error;
    } finally {
        if (connection) {
            await connection.end();
            console.log('🔌 数据库连接已关闭');
        }
    }
}

// 执行补充
if (require.main === module) {
    addQiankunGemAttributes()
        .then(() => {
            console.log('\n✅ 乾坤珠属性数据补充脚本执行完成');
            process.exit(0);
        })
        .catch((error) => {
            console.error('\n❌ 乾坤珠属性数据补充脚本执行失败:', error.message);
            process.exit(1);
        });
}

module.exports = { addQiankunGemAttributes };
